import { useState, useEffect } from "react";
import { useRouter } from "next/router";

export default function CreateRole() {
  const [name, setName] = useState("");
  const [permissions, setPermissions] = useState([]);
  const [selectedPermissions, setSelectedPermissions] = useState([]);
  const router = useRouter();

  useEffect(() => {
    const fetchPermissions = async () => {
      const res = await fetch("/api/permissions");
      const data = await res.json();
      setPermissions(data);
    };

    fetchPermissions();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const res = await fetch("/api/roles", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ name, permissions: selectedPermissions }),
    });
    if (res.ok) {
      router.push("/roles");
    }
  };

  const handlePermissionChange = (permissionId) => {
    setSelectedPermissions((prev) => {
      if (prev.includes(permissionId)) {
        return prev.filter((p) => p !== permissionId);
      } else {
        return [...prev, permissionId];
      }
    });
  };

  return (
    <form onSubmit={handleSubmit} className="container mx-auto">
      <h1 className="text-2xl font-bold my-4">创建角色</h1>
      <label>角色名称</label>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        className="border border-gray-300 p-2 w-full mb-4"
        required
      />
      <h2 className="text-xl font-semibold my-4">权限设置</h2>
      <div className="mb-4">
        {permissions.map((permission) => (
          <div key={permission.id} className="flex items-center">
            <input
              type="checkbox"
              id={permission.id}
              checked={selectedPermissions.includes(permission.id)}
              onChange={() => handlePermissionChange(permission.id)}
              className="mr-2"
            />
            <label htmlFor={permission.id}>{permission.name}</label>
          </div>
        ))}
      </div>
      <button type="submit" className="bg-blue-500 text-white p-2 rounded">
        创建
      </button>
    </form>
  );
}
